package com.lx.core.filter;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * Created by lanyxp on 2021/2/23 11:03
 * <P>cors前后端分离项目允许前端请求进行跨域</P>
 */
@Component
public class AppBootFiler {
    @Bean
    public FilterRegistrationBean<CorsFilter> corsFilterFilterRegistrationBean() {
        CorsConfiguration config = new CorsConfiguration();
        //DefaultValues 包含  config.setAllowCredentials(true) 允许处理cooks config.addAllowedMethod("*");
        config.applyPermitDefaultValues();
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<CorsFilter> beans = new FilterRegistrationBean(new CorsFilter(source));
        beans.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return beans;
    }
}
